package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.velocity.runtime.directive.contrib.For;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author LiLi
 * @since 2021-09-23
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void importData(MultipartFile multipartFile) {
        //调用easyexcel的上传方法，通过监听将上传的excel数据导入数据库
        try {
            EasyExcel.read(multipartFile.getInputStream(), ExcelDictDTO.class,new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<ExcelDictDTO> listDictData() {
//        List<Dict> dicts = baseMapper.selectList(null);
//        List<ExcelDictDTO> excelDictDTOS = new ArrayList<>();
//        for (Dict dict : dicts){
//            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
//            BeanUtils.copyProperties(dict,excelDictDTO);
//            excelDictDTOS.add(excelDictDTO);
//        }
        List<Dict> dicts = baseMapper.selectList(null);
        List<ExcelDictDTO> excelDictDTOS = dicts.stream().map(dictMap->{
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(dictMap,excelDictDTO);
            return excelDictDTO;
        }).collect(Collectors.toList());
        return excelDictDTOS;
    }

    //dict字典功能
    @Override
    public List<Dict> listByParentId(Long parentId) {
        List<Dict> dicts = new ArrayList<>();
        //查询缓存
        dicts= (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList" + parentId);

        if(null==dicts||dicts.size()<=0){
            //无缓存
            //去查询数据库
            dicts = getListByParentIdFromDb(parentId);

            if(null!=dicts&&dicts.size()>0){
                //数据库中有数据，同步缓存
                redisTemplate.opsForValue().set("srb:core:dictList" + parentId,dicts);
            }
        }

        return dicts;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        List<Dict> dicts = new ArrayList<>();
        // 根据dictCode找到parentId
        QueryWrapper<Dict> parentIdQueryWrapper = new QueryWrapper<>();
        parentIdQueryWrapper.eq("dict_code",dictCode);
        Dict dictParam = baseMapper.selectOne(parentIdQueryWrapper);
        if(null!=dictParam){
            // 查询db
            QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.eq("parent_id",dictParam.getId());
            dicts = baseMapper.selectList(dictQueryWrapper);
            for (Dict dict : dicts) {
                boolean b = hasChildren(dict.getId());
                dict.setHasChildren(b);
            }
        }
        return dicts;
    }

    private List<Dict> getListByParentIdFromDb(Long parentId) {
        //查询数据库
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id",parentId);
        List<Dict> dicts = baseMapper.selectList(dictQueryWrapper);
        for(Dict dict : dicts){
            boolean b =hasChildren(dict.getId());
            dict.setHasChildren(b);
        }
        return dicts;
    }

    private boolean hasChildren(Long id) {
        boolean b = false;

        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id",id);

        Integer integer = baseMapper.selectCount(dictQueryWrapper);

        if(integer>0){
            b = true;
        }
        return b;
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer valueId) {
        QueryWrapper<Dict> dictParentQueryWrapper = new QueryWrapper<>();
        dictParentQueryWrapper.eq("dict_code",dictCode);
        Dict dictParent = baseMapper.selectOne(dictParentQueryWrapper);

        Long parentId = dictParent.getId();

        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.select("name").eq("parent_id", parentId).eq("value", valueId);
        List<Object> objects = baseMapper.selectObjs(dictQueryWrapper);
        String name = (String)objects.get(0);

        return name;
    }
}
